Technical Q&A

Java 12 - Using Runtime.exec to open a URL (Updated 2-June-999)


Q: How would I open a URL in a browser from my Java application?

A: The simplest answer is to use the exec function of the java.lang.Runtime class and pass in the browser and the URL as parameters. The simple example below will present a file dialog to choose the browser to use, then launch the browser and open the specified URL:

import java.awt.Frame;
import java.awt.FileDialog;
import java.io.File;
import java.io.IOException;

public class ExecTest extends Frame
{

    public static void main(String[ ] args)
    {
        new ExecTest();
        System.exit(0);
    }

    public ExecTest()
    {
        String browserName;
        String url = "http://developer.apple.com/java/";

        //Set up a FileDialog for the user to locate the browser to use.        
        FileDialog fileDialog = new java.awt.FileDialog(this);
        fileDialog.setMode(FileDialog.LOAD);
        fileDialog.setTitle("Choose the browser to use:");
        fileDialog.setVisible(true);

        //Retrieve the path information from the dialog and verify it.        
       String resultPath = fileDialog.getDirectory();
        String resultFile = fileDialog.getFile();
        if(resultPath != null && resultPath.length()!= 0 &&           resultFile != null && resultFile.length() != 0)
        {
            File file = new File(resultPath + resultFile);
            if(file != null)
            {
                browserName = file.getPath();

                try
                {
                    //Launch the browser and pass it the desired URL
                    Runtime.getRuntime().exec(newString[ ] {browserName, url});
                }
                catch (IOException exc)
                {
                    exc.printStackTrace();
                }
            }
        }
    }
}

This example should be refined, if used in a real setting, to cache the browser information and only ask the user if the cached browser could not be located.

A more sophisticated approach that would not require the user to choose the browser could use JConfig to obtain the default browser information.

As an alternative to JConfig for the sole purpose of opening a URL in the user's default browser, one should consider BrowserLauncher by Eric Albert. BrowserLauncher is a Java class designed to allow programmers to open a user's default web browser entirely through Java, without requiring that any supplemental libraries be present and without stepping outside of JDK 1.1. BrowserLauncher is free for commercial and non-commercial use.


-- Levi Brown
-- Revised by Levi Brown
Worldwide Developer Technical Support

Technical Q&As | Contents
Previous Question | Next Question

To contact us, please use the Contact Us page.